package week_six;

import java.util.Arrays;

public class BestTimeToBuyAndSellStockIII_123 {
    public int maxProfit(int[] prices) {
        int Min_Value = (int) -1e9;

        int n = prices.length;
        int[] newPrices = new int[n + 1];
        for (int i = 1; i <= n; i++) newPrices[i] = prices[i - 1];

        int[][][] f = new int[2][2][3];
        Arrays.fill(f[0][0], Min_Value);
        Arrays.fill(f[0][1], Min_Value);
        f[0][0][0] = 0;

        for (int i = 1; i <= n; i++)
            for (int j = 0; j < 2; j++)
                for (int k = 0; k <= 2; k++) {
                    f[i & 1][j][k] = f[(i - 1) & 1][j][k];
                    if (j == 0) f[i & 1][0][k] = Math.max(f[i & 1][0][k], f[(i - 1) & 1][1][k] + newPrices[i]);
                    if (j == 1 && k > 0)
                        f[i & 1][1][k] = Math.max(f[i & 1][1][k], f[(i - 1) & 1][0][k - 1] - newPrices[i]);
                }

        int ans = 0;
        for (int k = 0; k <= 2; k++) {
            ans = Math.max(ans, f[n & 1][0][k]);
        }
        return ans;

    }
}
